<template>
  <div class="permission-management">
    <div class="page-header">
      <h2>权限管理</h2>
      <el-button 
        v-if="hasPermission('permission:add')"
        type="primary" 
        @click="handleAdd"
      >
        <el-icon><Plus /></el-icon>
        新增权限
      </el-button>
    </div>

    <!-- 权限树表格 -->
    <div class="table-container">
      <el-table
        :data="permissionTree"
        v-loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
      >
        <el-table-column prop="permissionName" label="权限名称" min-width="200">
          <template #default="{ row }">
            <span class="permission-name">{{ row.permissionName }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="permissionCode" label="权限编码" min-width="180">
          <template #default="{ row }">
            <code class="permission-code">{{ row.permissionCode }}</code>
          </template>
        </el-table-column>
        
        <el-table-column prop="permissionType" label="权限类型" width="120">
          <template #default="{ row }">
            <el-tag 
              :type="getPermissionTypeTag(row.permissionType)"
              size="small"
            >
              {{ getPermissionTypeName(row.permissionType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="resourceUrl" label="资源URL" min-width="200">
          <template #default="{ row }">
            <code v-if="row.resourceUrl" class="resource-url">{{ row.resourceUrl }}</code>
            <span v-else class="text-gray">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="method" label="HTTP方法" width="100">
          <template #default="{ row }">
            <el-tag 
              v-if="row.method"
              :type="getMethodTypeTag(row.method)"
              size="small"
            >
              {{ row.method }}
            </el-tag>
            <span v-else class="text-gray">-</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="sort" label="排序" width="80" align="center">
          <template #default="{ row }">
            <span class="sort-badge">{{ row.sort || 0 }}</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag 
              :type="row.status === 1 ? 'success' : 'danger'"
              size="small"
            >
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="hasPermission('permission:view')"
              type="info" 
              size="small" 
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button 
              v-if="hasPermission('permission:edit')"
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-if="hasPermission('permission:delete')"
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 权限表单对话框 -->
    <el-dialog 
      v-model="permissionDialogVisible" 
      :title="dialogTitle" 
      width="600px"
      @close="closePermissionDialog"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="120px"
        label-position="right"
      >
        <el-form-item label="权限名称" prop="permissionName">
          <el-input 
            v-model="permissionForm.permissionName" 
            placeholder="请输入权限名称"
            :disabled="isView"
          />
        </el-form-item>
        
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input 
            v-model="permissionForm.permissionCode" 
            placeholder="请输入权限编码，如：user:add"
            :disabled="isView"
          />
        </el-form-item>
        
        <el-form-item label="权限类型" prop="permissionType">
          <el-select 
            v-model="permissionForm.permissionType" 
            placeholder="请选择权限类型"
            style="width: 100%"
            :disabled="isView"
          >
            <el-option label="菜单权限" value="MENU" />
            <el-option label="操作权限" value="OPERATION" />
            <el-option label="数据权限" value="DATA" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="父权限" prop="parentId">
          <el-tree-select
            v-model="permissionForm.parentId"
            :data="parentPermissionOptions"
            :props="{ label: 'permissionName', value: 'id', children: 'children' }"
            placeholder="请选择父权限"
            check-strictly
            :disabled="isView"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="资源URL" prop="resourceUrl">
          <el-input 
            v-model="permissionForm.resourceUrl" 
            placeholder="请输入资源URL，如：/api/users/**"
            :disabled="isView"
          />
        </el-form-item>
        
        <el-form-item label="HTTP方法" prop="method">
          <el-select 
            v-model="permissionForm.method" 
            placeholder="请选择HTTP方法"
            style="width: 100%"
            :disabled="isView"
            clearable
          >
            <el-option label="GET" value="GET" />
            <el-option label="POST" value="POST" />
            <el-option label="PUT" value="PUT" />
            <el-option label="DELETE" value="DELETE" />
            <el-option label="ALL" value="ALL" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="排序" prop="sort">
          <el-input-number 
            v-model="permissionForm.sort" 
            :min="0" 
            :max="9999" 
            placeholder="请输入排序值"
            style="width: 100%"
            :disabled="isView"
          />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="permissionForm.status" :disabled="isView">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="权限描述" prop="description">
          <el-input 
            v-model="permissionForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入权限描述"
            :disabled="isView"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="closePermissionDialog">取消</el-button>
        <el-button 
          v-if="!isView"
          type="primary" 
          @click="confirmPermission" 
          :loading="permissionLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import request from '../utils/request'
import { usePermissions } from '../stores/permission'

const permissionTree = ref([])
const loading = ref(false)
const permissionDialogVisible = ref(false)
const permissionLoading = ref(false)
const isEdit = ref(false)
const isView = ref(false)
const permissionFormRef = ref()
const parentPermissionOptions = ref([])

const permissionForm = reactive({
  id: null,
  permissionName: '',
  permissionCode: '',
  permissionType: 'OPERATION',
  parentId: 0,
  resourceUrl: '',
  method: '',
  sort: 0,
  status: 1,
  description: ''
})

// 表单验证规则
const permissionRules = {
  permissionName: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '权限名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  permissionCode: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { min: 2, max: 50, message: '权限编码长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z][a-zA-Z0-9:_-]*$/, message: '权限编码格式不正确，只能包含字母、数字、冒号、下划线和连字符，且必须以字母开头', trigger: 'blur' }
  ],
  permissionType: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 0, max: 9999, message: '排序值范围为 0-9999', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 使用响应式权限检查
const { hasPermission } = usePermissions()

// 计算属性
const dialogTitle = computed(() => {
  if (isView.value) return '查看权限'
  return isEdit.value ? '编辑权限' : '新增权限'
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 获取权限类型标签样式
const getPermissionTypeTag = (type) => {
  switch (type) {
    case 'MENU': return 'success'
    case 'OPERATION': return 'primary'
    case 'DATA': return 'warning'
    default: return 'info'
  }
}

// 获取权限类型名称
const getPermissionTypeName = (type) => {
  switch (type) {
    case 'MENU': return '菜单'
    case 'OPERATION': return '操作'
    case 'DATA': return '数据'
    default: return '未知'
  }
}

// 获取HTTP方法标签样式
const getMethodTypeTag = (method) => {
  switch (method) {
    case 'GET': return 'success'
    case 'POST': return 'primary'
    case 'PUT': return 'warning'
    case 'DELETE': return 'danger'
    case 'ALL': return 'info'
    default: return ''
  }
}

// 获取权限列表
const fetchPermissions = async () => {
  try {
    loading.value = true
    const response = await request.get('/permission/list')
    permissionTree.value = response.data || []
  } catch (error) {
    console.error('获取权限列表失败:', error)
    ElMessage.error('获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 获取父权限选项
const fetchParentPermissionOptions = async () => {
  try {
    const response = await request.get('/permission/enabled')
    const permissions = response.data || []
    
    // 添加顶级选项
    parentPermissionOptions.value = [
      { id: 0, permissionName: '顶级权限', children: permissions }
    ]
  } catch (error) {
    console.error('获取父权限选项失败:', error)
    parentPermissionOptions.value = [{ id: 0, permissionName: '顶级权限', children: [] }]
  }
}

// 重置表单
const resetPermissionForm = () => {
  permissionForm.id = null
  permissionForm.permissionName = ''
  permissionForm.permissionCode = ''
  permissionForm.permissionType = 'OPERATION'
  permissionForm.parentId = 0
  permissionForm.resourceUrl = ''
  permissionForm.method = ''
  permissionForm.sort = 0
  permissionForm.status = 1
  permissionForm.description = ''
  
  if (permissionFormRef.value) {
    permissionFormRef.value.clearValidate()
  }
}

// 关闭权限对话框
const closePermissionDialog = () => {
  permissionDialogVisible.value = false
  isEdit.value = false
  isView.value = false
  resetPermissionForm()
}

// 新增权限
const handleAdd = async () => {
  isEdit.value = false
  isView.value = false
  resetPermissionForm()
  await fetchParentPermissionOptions()
  permissionDialogVisible.value = true
}

// 查看权限
const handleView = async (row) => {
  try {
    isView.value = true
    isEdit.value = false
    const response = await request.get(`/permission/${row.id}`)
    const permissionData = response.data
    
    permissionForm.id = permissionData.id
    permissionForm.permissionName = permissionData.permissionName
    permissionForm.permissionCode = permissionData.permissionCode
    permissionForm.permissionType = permissionData.permissionType
    permissionForm.parentId = permissionData.parentId
    permissionForm.resourceUrl = permissionData.resourceUrl
    permissionForm.method = permissionData.method
    permissionForm.sort = permissionData.sort
    permissionForm.status = permissionData.status
    permissionForm.description = permissionData.description
    
    await fetchParentPermissionOptions()
    permissionDialogVisible.value = true
  } catch (error) {
    console.error('获取权限信息失败:', error)
    ElMessage.error('获取权限信息失败')
  }
}

// 编辑权限
const handleEdit = async (row) => {
  try {
    isEdit.value = true
    isView.value = false
    const response = await request.get(`/permission/${row.id}`)
    const permissionData = response.data
    
    permissionForm.id = permissionData.id
    permissionForm.permissionName = permissionData.permissionName
    permissionForm.permissionCode = permissionData.permissionCode
    permissionForm.permissionType = permissionData.permissionType
    permissionForm.parentId = permissionData.parentId
    permissionForm.resourceUrl = permissionData.resourceUrl
    permissionForm.method = permissionData.method
    permissionForm.sort = permissionData.sort
    permissionForm.status = permissionData.status
    permissionForm.description = permissionData.description
    
    await fetchParentPermissionOptions()
    permissionDialogVisible.value = true
  } catch (error) {
    console.error('获取权限信息失败:', error)
    ElMessage.error('获取权限信息失败')
  }
}

// 删除权限
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限"${row.permissionName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await request.delete(`/permission/delete/${row.id}`)
    ElMessage.success('删除权限成功')
    await fetchPermissions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error)
      ElMessage.error('删除权限失败')
    }
  }
}

// 确认权限操作
const confirmPermission = async () => {
  try {
    await permissionFormRef.value.validate()
    
    permissionLoading.value = true
    
    if (isEdit.value) {
      await request.put(`/permission/update/${permissionForm.id}`, permissionForm)
      ElMessage.success('修改权限成功')
    } else {
      await request.post('/permission/add', permissionForm)
      ElMessage.success('新增权限成功')
    }
    
    closePermissionDialog()
    await fetchPermissions()
  } catch (error) {
    console.error('操作权限失败:', error)
    ElMessage.error('操作权限失败')
  } finally {
    permissionLoading.value = false
  }
}

onMounted(async () => {
  await fetchPermissions()
})
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e6e6e6;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.permission-name {
  font-weight: 500;
  color: #303133;
}

.permission-code {
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 12px;
  color: #606266;
}

.resource-url {
  background: #f0f9ff;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
  font-size: 12px;
  color: #0ea5e9;
}

.sort-badge {
  background: #e1f3ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.text-gray {
  color: #909399;
  font-style: italic;
}

:deep(.el-table) {
  .el-table__row {
    cursor: pointer;
  }
  
  .el-table__row:hover {
    background-color: #f5f7fa;
  }
}

:deep(.el-dialog__body) {
  padding: 20px 20px 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .permission-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .table-container {
    padding: 16px;
    overflow-x: auto;
  }
  
  :deep(.el-dialog) {
    width: 95vw !important;
    margin: 5vh auto;
  }
}
</style> 